<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="考试名称" prop="examinationName">
        <el-input
          v-model="queryParams.examinationName"
          placeholder="请输入考试名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="考试类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择考试类型" clearable size="small">
          <el-option
            v-for="dict in this.getDictDatas(DICT_TYPE.EXAM_TYPE)"
            :key="dict.value"
            :value="parseInt(dict.value)"
            :label="dict.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['exam:examination:create']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['exam:examination:export']"
        >导出</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-plus" size="mini" @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['exam:examination:export']">一键组卷</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <el-table-column label="考试名称" align="center" prop="examinationName"/>
      <el-table-column label="考试类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.EXAM_TYPE" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="考试注意事项" align="center" prop="attention" /> -->
      <el-table-column label="考试开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="考试结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总分" align="center" prop="totalScore"/>
      <el-table-column label="合格分数" align="center" prop="passScore"/>
      <!-- <el-table-column label="考试状态" align="center" prop="status" >
        <template slot-scope="scope">
           <dict-tag :type="DICT_TYPE.EXAM_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>-->
      <!-- <el-table-column label="图片封面" align="center" prop="avatarUrl" />
      <el-table-column label="所属课程" align="center" prop="courseId" />
      <el-table-column label="备注" align="center" prop="remark" />-->
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column label="系统编号" align="center" prop="applicationCode" />
       <el-table-column label="所属机构编码" align="center" prop="deptId" />
      <el-table-column label="是否章节测试(0是,2否)" align="center" prop="state" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['exam:examination:update']"
          >修改</el-button>-->

          <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="toSubject(scope.row.id)"
            v-hasPermi="['exam:examination:update']"
          >手动组卷</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="aoToSubject(scope.row.id)"
            v-hasPermi="['exam:examination:update']"
          >自动组卷</el-button>
          <el-dropdown
            size="mini"
            @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="['exam:examination:update','exam:examination:update']"
          >
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <!-- <router-link :to="'/exam/examination/subject/' + scope.row.id" class="link-type">
                <el-dropdown-item
                  icon="el-icon-tickets"
                  v-hasPermi="['exam:examination:update']"
                >题目管理</el-dropdown-item>
              </router-link>-->
              <el-dropdown-item
                command="handleUpdate"
                icon="el-icon-edit"
                v-hasPermi="['exam:examination:update']"
              >修改</el-dropdown-item>
              <el-dropdown-item
                command="handleDelete"
                icon="el-icon-delete"
                v-hasPermi="['exam:examination:delete']"
              >删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="考试类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择考试类型">
            <el-option
              v-for="dict in this.getDictDatas(DICT_TYPE.EXAM_TYPE)"
              :key="dict.value"
              :value="parseInt(dict.value)"
              :label="dict.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="考试名称" prop="examinationName">
          <el-input v-model="form.examinationName" placeholder="请输入考试名称"/>
        </el-form-item>

        <!-- <el-form-item label="所属课程" prop="courseId">
          <el-input v-model="form.courseId" placeholder="请输入所属课程" />
        </el-form-item>-->
        <el-form-item label="所属分类" prop="categoryId">
          <treeselect
            v-model="form.categoryId"
            :options="cateOptions"
            :show-count="true"
            :clearable="false"
            placeholder="请选择归属分类"
            :normalizer="normalizer"
          />
        </el-form-item>
        <el-form-item label="所属活动" prop="activityId">
          <el-select v-model="form.activityId" placeholder="请选择所属活动">
            <el-option
              v-for="item in activityOptions"
              :key="item.id"
              :value="item.id"
              :label="item.activityName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="考试开始时间" prop="startTime">
          <el-date-picker
            clearable
            v-model="form.startTime"
            type="datetime"
            value-format="timestamp"
            placeholder="选择考试开始时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="考试结束时间" prop="endTime">
          <el-date-picker
            clearable
            v-model="form.endTime"
            type="datetime"
            value-format="timestamp"
            placeholder="选择考试结束时间"
          ></el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="考试状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.EXAM_STATUS)"
                      :key="dict.value" :label="parseInt(dict.value)">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>-->
        <el-form-item label="总分" prop="totalScore">
          <el-input-number size="medium" v-model="form.totalScore"></el-input-number>
        </el-form-item>
        <el-form-item label="合格分数" prop="passScore">
          <el-input-number size="medium" v-model="form.passScore"></el-input-number>
        </el-form-item>
        <el-form-item label="图片封面" prop="avatarUrl">
          <imageUpload v-model="form.avatarUrl"/>
        </el-form-item>
        <el-form-item label="考试注意事项" prop="attention">
          <tinymce v-model="form.attention" :key="tinymceFlag"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
        <!-- <el-form-item label="系统编号" prop="applicationCode">
          <el-input v-model="form.applicationCode" placeholder="请输入系统编号" />
        </el-form-item>
        <el-form-item label="所属机构编码" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入所属机构编码" />
        </el-form-item>
        <el-form-item label="是否章节测试" prop="state">
          <el-radio-group v-model="form.state">
            <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.IS_TRUE)"
                      :key="dict.value" :label="parseInt(dict.value)">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 自动组卷 -->

    <!-- 自动组卷弹框 -->
    <el-dialog title="自动组卷" :visible.sync="openGroupExam" width="700px" append-to-body>
      <el-form ref="aoToAddform" :model="aoToAddform" :rules="aoToAddrules">
        <el-form-item label prop="choicesType">
          <div style="font-weight:700;">各类题目占比</div>
          <div class="flex" v-for="item in topicTypeList">
            <span>{{item.categoryName}}</span>
            <el-input
              class="inPut"
              :style="{'width':350 + 'px'}"
              v-model="item.count"
              placeholder="请输入所占比例"
            />
          </div>
        </el-form-item>
        <!--  -->
        <div>单选题</div>
        <div class="betwen">
          <el-form-item label="题目数量" prop="onecount">
            <el-input v-model="aoToAddform.onecount" placeholder="请输入数量"/>
          </el-form-item>
          <el-form-item label="难度等级" prop="onelevel">
            <!-- <el-rate v-model="aoToAddform.level" show-text :texts="texts"></el-rate> -->
            <el-select v-model="aoToAddform.onelevel" placeholder="请选择难易程度">
              <el-option v-for="item in texts" :key="item" :value="item" :label="item"/>
            </el-select>
          </el-form-item>
        </div>
        <div>多选题</div>
        <div class="betwen">
          <el-form-item label="题目数量" prop="morecount">
            <el-input v-model="aoToAddform.morecount" placeholder="请输入数量"/>
          </el-form-item>
          <el-form-item label="难度等级" prop="morelevel">
            <!-- <el-rate v-model="aoToAddform.level" show-text :texts="texts"></el-rate> -->
            <el-select v-model="aoToAddform.morelevel" placeholder="请选择难易程度">
              <el-option v-for="item in texts" :key="item" :value="item" :label="item"/>
            </el-select>
          </el-form-item>
        </div>
        <div>判断题</div>
        <div class="betwen">
          <el-form-item label="题目数量" prop="ifcount">
            <el-input v-model="aoToAddform.ifcount" placeholder="请输入数量"/>
          </el-form-item>
          <el-form-item label="难度等级" prop="iflevel">
            <!-- <el-rate v-model="aoToAddform.level" show-text :texts="texts"></el-rate> -->
            <el-select v-model="aoToAddform.iflevel" placeholder="请选择难易程度">
              <el-option v-for="item in texts" :key="item" :value="item" :label="item"/>
            </el-select>
          </el-form-item>
        </div>
        <div>填空题</div>
        <div class="betwen">
          <el-form-item label="题目数量" prop="docount">
            <el-input v-model="aoToAddform.docount" placeholder="请输入数量"/>
          </el-form-item>
          <el-form-item label="难度等级" prop="dolevel">
            <!-- <el-rate v-model="aoToAddform.level" show-text :texts="texts"></el-rate> -->
            <el-select v-model="aoToAddform.dolevel" placeholder="请选择难易程度">
              <el-option v-for="item in texts" :key="item" :value="item" :label="item"/>
            </el-select>
          </el-form-item>
        </div>
        <div>简答题</div>
        <div class="betwen">
          <el-form-item label="题目数量" prop="shortcount">
            <el-input v-model="aoToAddform.shortcount" placeholder="请输入数量"/>
          </el-form-item>
          <el-form-item label="难度等级" prop="shorlevel">
            <!-- <el-rate v-model="aoToAddform.level" show-text :texts="texts"></el-rate> -->
            <el-select v-model="aoToAddform.shorlevel" placeholder="请选择难易程度">
              <el-option v-for="item in texts" :key="item" :value="item" :label="item"/>
            </el-select>
          </el-form-item>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="aoToAddsubmitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  createExamination,
  updateExamination,
  deleteExamination,
  getExamination,
  getExaminationPage,
  exportExaminationExcel,
  aoToExaminationSubject
} from "@/api/exam/examination";

import { getSimpleList } from "@/api/examination/subjectCategory";
import { getActivityPage } from "@/api/exam/activity";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import ImageUpload from "@/components/ImageUpload";
import tinymce from "@/components/tinymce";
export default {
  name: "examination",
  components: {
    Treeselect,
    ImageUpload,
    tinymce
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试卷信息列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        examinationName: null,
        type: null
      },
      activityOptions: [1, 2, 3],
      // 表单参数
      form: {},
      aoToAddform: {
        level: "",
        count: ""
      },
      texts: ["容易", "偏易", "适中", "偏难", "困难"],
      // 表单校验
      rules: {
        examinationName: [
          { required: true, message: "考试名称不能为空", trigger: "blur" }
        ],
        totalScore: [
          { required: true, message: "总分不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "考试类型不能为空", trigger: "blur" }
        ],
        categoryId: [
          { required: true, message: "所属分类不能为空", trigger: "blur" }
        ],
        activityId: [
          { required: true, message: "所属活动不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
        passScore: [
          { required: true, message: "合格分数不能为空", trigger: "blur" }
        ],
        avatarUrl: [
          { required: true, message: "封面图片不能为空", trigger: "blur" }
        ],
        attention: [
          { required: true, message: "考试注意事项不能为空", trigger: "blur" }
        ]
      },
      //
      aoToAddrules: {
        categoryId: [
          { required: true, message: "所属分类不能为空", trigger: "blur" }
        ],
        examinationName: [
          { required: true, message: "考试名称不能为空", trigger: "blur" }
        ],
        subjectCount: [
          { required: true, message: "共计题目不能为空", trigger: "blur" }
        ],
        totalScore: [
          { required: true, message: "总分不能为空", trigger: "blur" }
        ],
        type: [{ required: true, message: "考试类型不能为空", trigger: "blur" }]
      },
      cateOptions: undefined,
      categoryName: undefined,
      tinymceFlag: 1,
      openGroupExam: false,
      countList: [],
      //难度等级
      topicTypeList: [] // 各类题目类型
      // addTestForm: {
      //   topicTypeList: [],
      //   onecount: 1, // 单选题目数量
      //   onLevel: '',
      //   ...
      // }
      // testForm: {
      //   topicTypeList: [],
      //   oneChoice: {
      //     count: '',
      //     level: ''
      //   },
      //   twoChoice: {
      //     count: '',
      //     level: ''
      //   }
      // }
    };
  },
  created() {
    this.getList();
    this.getTreeselect();
    // this.getcountList();
    // this.aoToExaminationSubjectList();
  },
  methods: {
    // getcountList() {
    //   this.countList = cateOptions[0].children.map(item => {
    //     return (item.count = "");
    //   });
    // },
    // async aoToExaminationSubjectList() {
    //   const res = await aoToExaminationSubject();
    //   console.log(res);
    // },

    toSubject(id) {
      this.$router.push(`/exam/examination/subject/${id}`);
    },
    aoToSubject() {
      this.openGroupExam = true;
      console.log(this.countList);
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getExaminationPage(this.queryParams).then(response => {
        console.log(response);
        this.list = response.data.list;
        // console.log(this.list);

        this.total = parseInt(response.data.total);
        this.loading = false;
      });
      //查询活动列表
      getActivityPage().then(response => {
        // console.log(response);

        this.activityOptions = response.data.list;
        // console.log(this.activityOptions);
      });
    },
    /** 查询课程树形 */
    getTreeselect() {
      getSimpleList().then(response => {
        for (let i = 0; i < response.data.length; i++) {
          response.data[i].id = parseInt(response.data[i].id);
          response.data[i].parentId = parseInt(response.data[i].parentId);
        }
        // 处理 cateOptions 参数
        this.cateOptions = [];
        this.cateOptions.push(...this.handleTree(response.data, "id"));
        this.topicTypeList = this.cateOptions[0].children.map(item => {
          return {
            ...item,
            count: ""
          };
        });
        // this.topicTypeList = this.cateOptions[0].children;
        // this.topicTypeList.forEach(item => {
        //   item.count = "";
        // });
        console.log(this.topicTypeList, 22222);
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.openGroupExam = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        examinationName: undefined,
        type: undefined,
        attention: undefined,
        startTime: undefined,
        endTime: undefined,
        totalScore: undefined,
        status: 1,
        avatarUrl: undefined,
        courseId: undefined,
        remark: undefined,
        applicationCode: undefined,
        deptId: this.$store.getters.deptId,
        state: undefined
      };
      this.tinymceFlag++;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加试卷信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getExamination(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改试卷信息";
      });
    },
    //更多操作按钮触发
    handleCommand(command, row) {
      switch (command) {
        case "handleExam":
          this.handleExam(row);
          break;
        case "handleDelete":
          this.handleDelete(row);
          break;
        case "handleUpdate":
          this.handleUpdate(row);
          break;
        default:
          break;
      }
    },
    //题目管理按钮触发
    handleExam(row) {
      this.$router.replace("/exam/examination/subject/" + row.id);
    },
    /** 提交按钮 */
    submitForm() {
      // console.log(this.form);

      this.$refs["form"].validate(valid => {
        // if (!valid) {
        //   return;
        // }
        // 修改的提交
        if (this.form.id != null) {
          updateExamination(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createExamination(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    aoToAddsubmitForm() {
      console.log(this.aoToAddform, 1111);
      console.log(this.topicTypeList, 33333);
      return;

      this.$refs["aoToAddform"].validate(async valid => {
        // const addForm = {
        //   categoryId: row.categoryId,
        //   examinationId: this.$route.params.id,
        //   subjectId: row.id,
        //   type: row.choicesType
        // };
        console.log(this.$route);

        const data = {
          categoryId: this.aoToAddform.categoryId,
          // examinationId: this.aoToAddform.examinationName,
          subjectCount: parseInt(this.aoToAddform.subjectCount),
          totalScore: parseInt(this.aoToAddform.totalScore)
        };
        const test = {
          totalScore: 98,
          subjectRandVOList: [
            {
              categoryId: this.aoToAddform.categoryId,
              subjectCount: 57,
              choicesType: this.aoToAddform.choicesType,
              tenantId: 85,
              subjectScore: 36
            }
          ],
          subjectCount: 34,
          // categoryId: 61,
          categoryId: this.aoToAddform.categoryId,

          examinationId: "47"
        };
        console.log(data);
        console.log(this.aoToAddform);
        // const res = await aoToExaminationSubject(this.aoToAddform);
        console.log(res);
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal
        .confirm('是否确认删除试卷信息编号为"' + id + '"的数据项?')
        .then(function() {
          return deleteExamination(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = { ...this.queryParams };
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal
        .confirm("是否确认导出所有试卷信息数据项?")
        .then(() => {
          this.exportLoading = true;
          return exportExaminationExcel(params);
        })
        .then(response => {
          this.$download.excel(response, "试卷信息.xls");
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    // 格式化课程树的下拉框
    normalizer(node) {
      return {
        id: node.id,
        label: node.categoryName,
        children: node.children
      };
    }
  }
};
</script>
<style lang="scss" 

>
.betwen {
  display: flex;
  justify-content: space-around;
}
.flex {
  display: flex;
  span {
    margin-bottom: 5px;
  }
}
.inPut {
  position: absolute;
  right: 50px;
}
</style>
